/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.controller;

import com.minierp.bean.LoanBillBean;
import com.minierp.bean.UserBean;
import com.minierp.dao.BankAccountBalanceDao;
import com.minierp.dao.BankAccountDao;
import com.minierp.dao.CodeRuleDao;
import com.minierp.dao.DepartmentDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.LoanBillDao;
import com.minierp.dao.SerialNumberDao;
import com.minierp.err.NotAllowException;
import com.minierp.err.PermissionDennyException;
import com.minierp.helper.EncCommonHelper;
import com.minierp.helper.PageHelper;
import com.minierp.model.CodeRule;
import com.minierp.model.EnterpriseInfo;
import com.minierp.model.LoanBill;
import com.minierp.model.TallySet;
import com.minierp.service.LoanBillService;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.dao.CannotAcquireLockException;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

public class LoanBillFormCtr extends SimpleFormController {
	private DepartmentDao departmentDao;
	private BankAccountDao bankAccountDao;
	private LoanBillDao loanBillDao;
	private CodeRuleDao codeRuleDao;
	private SerialNumberDao serialNumberDao;
	private BankAccountBalanceDao bankAccountBalanceDao;
	private IdGenerator idGenerator;
	private LoanBillService loanBillService;

	protected Map referenceData(HttpServletRequest request) throws Exception {
		HashMap refData = new HashMap();
		String id = request.getParameter("id");
		if (id == null) {
			id = "";
		}

		refData.put("id", id);
		String retVal = request.getParameter("ret_val");
		if (retVal == null) {
			retVal = "";
		}

		refData.put("retVal", retVal);
		refData.put("departmentList", this.departmentDao.getList(true));
		List baList = this.bankAccountDao.getList("", "");
		EnterpriseInfo ent = EncCommonHelper.getEnterpriseInfo(request);
		UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
		long dfTsId = 0L;
		long specId = 0L;
		if (id != null && !id.equals("")) {
			LoanBill bb = (LoanBill) this.loanBillDao.get(LoanBill.class,
					Long.parseLong(id));
			specId = bb.getBankAccountId();
			dfTsId = bb.getTallySetId();
		} else {
			dfTsId = ub.getUser().getDfTsId();
		}

		refData.put("bankAccountList",
				PageHelper.parseBaList(baList, ent, ub, dfTsId, specId));
		return refData;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String id = request.getParameter("id");
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		LoanBillBean form = new LoanBillBean();
		LoanBill loanBill;
		if (id != null && !id.equals("")) {
			loanBill = (LoanBill) this.loanBillDao.get(LoanBill.class,
					Long.parseLong(id));
			if (loanBill == null) {
				throw new Exception("Record not found for id:" + id);
			}

			TallySet cr1 = (TallySet) this.loanBillDao.get(TallySet.class,
					loanBill.getTallySetId());
			form.setSychronizeValue(loanBill.getUpdateTime().getTime());
			if (cr1 != null) {
				form.setTallySetName(cr1.getTitle());
			}

			form.setOldId(loanBill.getId());
			form.setCostStr(loanBill.getCost().toString());
			form.setLoanDateStr(sf.format(loanBill.getLoanDate()));
			form.setLoanBill(loanBill);
			if (loanBill.getAttachFile() != null
					&& !loanBill.getAttachFile().equals("")) {
				int ub1 = loanBill.getAttachFile().lastIndexOf("/");
				form.setAttachFileName(loanBill.getAttachFile().substring(
						ub1 + 1));
			}
		} else {
			String cr = request.getParameter("type");
			if (cr == null) {
				cr = "";
			}

			loanBill = new LoanBill();
			UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
			String billType;
			if (cr.equals("TEMP")) {
				billType = request.getParameter("template_id");
				LoanBill billId1 = (LoanBill) this.loanBillDao.get(
						LoanBill.class, Long.parseLong(billType));
				if (billId1 == null) {
					throw new Exception("Template LoanBill not found for id "
							+ billType);
				}

				loanBill.setBillType(billId1.getBillType());
				loanBill.setBankAccountId(billId1.getBankAccountId());
				loanBill.setDepartmentId(billId1.getDepartmentId());
				loanBill.setLoanDate(billId1.getLoanDate());
				loanBill.setManagerId(billId1.getManagerId());
				loanBill.setManagerName(billId1.getManagerName());
				loanBill.setRpName(billId1.getRpName());
				loanBill.setMark(billId1.getMark());
				loanBill.setTallySetId(ub.getUser().getDfTsId());
				form.setTallySetName(ub.getDfTsName());
			} else {
				String billId;
				if (!cr.equals("COUNT")) {
					if (cr.equals("BILL")) {
						billType = request.getParameter("bill_type");
						billId = request.getParameter("bill_id");
						loanBill.setBillType(billType);
						loanBill.setManagerId(ub.getStaffer().getId());
						loanBill.setManagerName(ub.getStaffer()
								.getStafferName());
						loanBill.setDepartmentId(ub.getStaffer()
								.getDepartmentId());
						loanBill.setRpName(ub.getStaffer().getStafferName());
						loanBill.setTallySetId(ub.getUser().getDfTsId());
						form.setTallySetName(ub.getDfTsName());
						LoanBill tf1 = (LoanBill) this.loanBillDao.get(
								LoanBill.class, Long.parseLong(billId));
						if (tf1 != null) {
							loanBill.setBankAccountId(tf1.getBankAccountId());
							loanBill.setDepartmentId(tf1.getDepartmentId());
							loanBill.setManagerId(tf1.getManagerId());
							loanBill.setManagerName(tf1.getManagerName());
							loanBill.setRpName(tf1.getRpName());
							loanBill.setCost((new BigDecimal(0)).subtract(tf1
									.getCost()));
							if (loanBill.getBillType().equals("IN")) {
								loanBill.setMark("还" + tf1.getRpName()
										+ tf1.getCost() + "元");
							} else {
								loanBill.setMark(tf1.getRpName() + "还款"
										+ tf1.getCost() + "元");
							}

							form.setCostStr(loanBill.getCost().toString());
						}
					} else {
						billType = request.getParameter("bill_type");
						loanBill.setBillType(billType);
						loanBill.setManagerId(ub.getStaffer().getId());
						loanBill.setManagerName(ub.getStaffer()
								.getStafferName());
						loanBill.setDepartmentId(ub.getStaffer()
								.getDepartmentId());
						loanBill.setRpName(ub.getStaffer().getStafferName());
						loanBill.setTallySetId(ub.getUser().getDfTsId());
						form.setTallySetName(ub.getDfTsName());
					}
				} else {
					billType = request.getParameter("bill_type");
					billId = request.getParameter("ts_id");
					String tf = request.getParameter("rp");
					String cost = request.getParameter("cost");
					loanBill.setBillType(billType);
					loanBill.setManagerId(ub.getStaffer().getId());
					loanBill.setManagerName(ub.getStaffer().getStafferName());
					loanBill.setDepartmentId(ub.getStaffer().getDepartmentId());
					loanBill.setRpName(ub.getStaffer().getStafferName());
					loanBill.setTallySetId(ub.getUser().getDfTsId());
					form.setTallySetName(ub.getDfTsName());
					if (billId != null && !billId.equals("")) {
						TallySet mark = (TallySet) this.loanBillDao.get(
								TallySet.class, Long.parseLong(billId));
						if (mark != null) {
							loanBill.setTallySetId(mark.getId());
							form.setTallySetName(mark.getTitle());
						}
					}

					if (tf != null && !tf.equals("")) {
						loanBill.setRpName(tf);
					}

					if (cost != null && !cost.equals("")) {
						loanBill.setCost((new BigDecimal(0))
								.subtract(new BigDecimal(cost)));
						String mark1 = "";
						if (loanBill.getBillType() != null
								&& loanBill.getBillType().equals("IN")) {
							mark1 = "还" + loanBill.getRpName() + cost + "元";
						} else if (loanBill.getBillType() != null
								&& loanBill.getBillType().equals("OUT")) {
							mark1 = loanBill.getRpName() + "还款" + cost + "元";
						}

						loanBill.setMark(mark1);
						form.setCostStr(loanBill.getCost().toString());
					}
				}
			}

			loanBill.setCreaterId(ub.getStaffer().getId());
			loanBill.setCreaterName(ub.getStaffer().getStafferName());
			form.setLoanDateStr(sf.format(loanBill.getLoanDate()));
			form.setLoanBill(loanBill);
			if (loanBill.getBillType() != null
					&& loanBill.getBillType().equals("IN")) {
				if (!EncCommonHelper.checkPrivilege(request, "LOAN_IN")) {
					throw new PermissionDennyException("Permission Denny");
				}
			} else if (loanBill.getBillType() != null
					&& loanBill.getBillType().equals("OUT")
					&& !EncCommonHelper.checkPrivilege(request, "LOAN_OUT")) {
				throw new PermissionDennyException("Permission Denny");
			}
		}

		CodeRule cr2 = null;
		if (loanBill.getBillType() != null
				&& loanBill.getBillType().equals("IN")) {
			cr2 = this.codeRuleDao.get("LOAN_BILL_IN");
		} else if (loanBill.getBillType() != null
				&& loanBill.getBillType().equals("OUT")) {
			cr2 = this.codeRuleDao.get("LOAN_BILL_OUT");
		}

		if (cr2 == null) {
			throw new Exception("Code rule not found for loan bill");
		} else {
			form.setCodeRule(cr2);
			return form;
		}
	}

	protected void onBind(HttpServletRequest request, Object command)
			throws Exception {
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		ModelAndView mv = new ModelAndView(this.getSuccessView());
		String id = request.getParameter("id");
		String examine = request.getParameter("examine");
		UserBean ub = EncCommonHelper.getCurrentUserAccount(request);
		LoanBillBean form = (LoanBillBean) command;
		LoanBill obj = form.getLoanBill();
		obj.setRpName(obj.getRpName().trim());
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("attach_file");
		String continueFlag;
		String alertType;
		String printFlag;
		if (multipartFile != null && !multipartFile.isEmpty()) {
			continueFlag = multipartFile.getOriginalFilename();
			alertType = EncCommonHelper.getExtendName(continueFlag);
			printFlag = EncCommonHelper.getUploadVirtualPath(this
					.getServletContext());
			String realPath = this.getServletContext().getRealPath(printFlag);
			String fileName = ub.getUser().getId() + "_"
					+ System.currentTimeMillis() + "." + alertType;
			FileCopyUtils.copy(multipartFile.getBytes(), new File(realPath
					+ System.getProperty("file.separator") + fileName));
			obj.setAttachFile(printFlag + fileName);
		}

		if (examine != null && examine.equals("1")) {
			continueFlag = "";
			if (obj.getBillType().equals("IN")) {
				continueFlag = "LOAN_IN_EXAM";
			} else {
				continueFlag = "LOAN_OUT_EXAM";
			}

			if (!EncCommonHelper.checkPrivilege(request, continueFlag)) {
				throw new Exception("Permission deny!");
			}

			obj.setExamined("Y");
			if (ub.getStaffer() != null) {
				obj.setExaminerId(ub.getStaffer().getId());
				obj.setExaminerName(ub.getStaffer().getStafferName());
			}
		} else {
			obj.setExamined("N");
		}

		if (id != null && !id.equals("")) {
			if (obj.getBillType().equals("IN")) {
				continueFlag = "LOAN_IN";
			} else {
				continueFlag = "LOAN_OUT";
			}

			if (!EncCommonHelper.checkPrivilege(request, continueFlag)) {
				throw new Exception("Permission deny!");
			}

			try {
				this.loanBillService.txUpdate(form, this.loanBillDao,
						this.idGenerator, this.bankAccountBalanceDao);
			} catch (CannotAcquireLockException arg17) {
				EncCommonHelper.setAlertMessage(request, "事务冲突故障，请重新操作！");
				return this.showForm(request, errors, this.getFormView());
			} catch (NotAllowException arg18) {
				EncCommonHelper.setAlertMessage(request, arg18.getMessage());
				return this.showForm(request, errors, this.getFormView());
			}
		} else {
			try {
				this.loanBillService.txInsert(form, this.loanBillDao,
						this.serialNumberDao, this.idGenerator,
						this.bankAccountBalanceDao);
			} catch (CannotAcquireLockException arg19) {
				EncCommonHelper.setAlertMessage(request, "事务冲突故障，请重新操作！");
				return this.showForm(request, errors, this.getFormView());
			} catch (NotAllowException arg20) {
				EncCommonHelper.setAlertMessage(request, arg20.getMessage());
				return this.showForm(request, errors, this.getFormView());
			}
		}

		mv.addObject("returnValue", String.valueOf(obj.getId()));
		continueFlag = request.getParameter("continue_flag");
		alertType = request.getParameter("alert_type");
		printFlag = request.getParameter("print_flag");
		if (continueFlag != null && !continueFlag.equals("")) {
			if (continueFlag.equals("NEW")) {
				EncCommonHelper.setAlertMessage(request, "保存成功！");
				mv = new ModelAndView(
						"redirect:/finance/LoanBillNew.ihtm?ret_val=1&bill_type="
								+ obj.getBillType() + "&alert_type="
								+ alertType);
			} else if (continueFlag.equals("COPY")) {
				EncCommonHelper.setAlertMessage(request, "保存成功！");
				mv = new ModelAndView(
						"redirect:/finance/LoanBillNew.ihtm?ret_val=1&template_id="
								+ obj.getId() + "&alert_type=" + alertType);
			}
		} else if (printFlag != null && printFlag.equals("REDI")) {
			mv = new ModelAndView("redirect:/finance/LoanBillPrint.ihtm?id="
					+ obj.getId());
		} else if (printFlag != null && printFlag.equals("NEW_WIN")) {
			mv.addObject("openWin",
					"/finance/LoanBillPrint.ihtm?id=" + obj.getId());
			mv.addObject("openWinWidth", "900");
			mv.addObject("openWinHeight", "300");
		} else if (alertType == null || !alertType.equals("NONE")) {
			EncCommonHelper.setAlertMessage(request, "保存成功！");
			if (alertType != null && alertType.equals("FORM")) {
				mv = new ModelAndView(new RedirectView(
						"/finance/LoanBillEdit.ihtm?ret_val=1&id="
								+ obj.getId() + "&alert_type=" + alertType));
			}
		}

		mv.addObject("alertType", alertType);
		return mv;
	}

	public CodeRuleDao getCodeRuleDao() {
		return this.codeRuleDao;
	}

	public void setCodeRuleDao(CodeRuleDao codeRuleDao) {
		this.codeRuleDao = codeRuleDao;
	}

	public DepartmentDao getDepartmentDao() {
		return this.departmentDao;
	}

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public IdGenerator getIdGenerator() {
		return this.idGenerator;
	}

	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}

	public SerialNumberDao getSerialNumberDao() {
		return this.serialNumberDao;
	}

	public void setSerialNumberDao(SerialNumberDao serialNumberDao) {
		this.serialNumberDao = serialNumberDao;
	}

	public BankAccountDao getBankAccountDao() {
		return this.bankAccountDao;
	}

	public void setBankAccountDao(BankAccountDao bankAccountDao) {
		this.bankAccountDao = bankAccountDao;
	}

	public LoanBillDao getLoanBillDao() {
		return this.loanBillDao;
	}

	public void setLoanBillDao(LoanBillDao loanBillDao) {
		this.loanBillDao = loanBillDao;
	}

	public LoanBillService getLoanBillService() {
		return this.loanBillService;
	}

	public void setLoanBillService(LoanBillService loanBillService) {
		this.loanBillService = loanBillService;
	}

	public BankAccountBalanceDao getBankAccountBalanceDao() {
		return this.bankAccountBalanceDao;
	}

	public void setBankAccountBalanceDao(
			BankAccountBalanceDao bankAccountBalanceDao) {
		this.bankAccountBalanceDao = bankAccountBalanceDao;
	}
}